package com.example.niuke.controller;

import com.example.niuke.entity.Event;
import com.example.niuke.entity.User;
import com.example.niuke.event.EventProducer;
import com.example.niuke.service.LikeService;
import com.example.niuke.util.CommunityConstant;
import com.example.niuke.util.CommunityUtil;
import com.example.niuke.util.HostHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;

@Controller
public class LikeController implements CommunityConstant {
    /**
     * Auther sun
     * DATE 2022/4/18 10:06
     * VERSION 1.0
     */

    @Resource
    private LikeService likeService;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private EventProducer eventProducer;

    @PostMapping("/like")
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId) {
        User user = hostHolder.getUser();

        //实现点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);


        HashMap<String, Object> data = new HashMap<>();
        data.put("postId",postId);
        if(likeStatus == 1) {
            Event event = new Event().builder()
                    .topic(TOPIC_LIKE)
                    .userId(hostHolder.getUser().getId())
                    .entityType(entityType)
                    .entityId(entityId)
                    .entityUserId(entityUserId)
                    .data(data)
                    .build();
            eventProducer.fireEvent(event);
        }


        return CommunityUtil.getJSONString(0, null, map);
    }
}
